import { 
  saveApplication, 
  findApplicationById, 
  findApplicationsByJobId, 
  findApplicationsByApplicantId, 
  findAllApplications,
  updateApplication
} from './storageService';
import { generateId } from './storageService';

// 提交职位申请
export function submitApplication(jobId, applicantId, resume) {
  // 验证必填字段
  if (!jobId || !applicantId || !resume) {
    throw new Error('请填写所有必填字段');
  }

  // 检查是否已申请过该职位
  const existingApplications = findApplicationsByApplicantId(applicantId);
  const alreadyApplied = existingApplications.some(app => app.jobId === jobId);
  if (alreadyApplied) {
    throw new Error('您已申请过该职位');
  }

  // 创建申请对象
  const application = {
    id: generateId(),
    jobId: jobId,
    applicantId: applicantId,
    resume: resume,
    status: 'pending', // 默认状态为待处理
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  };

  // 保存申请到存储
  if (saveApplication(application)) {
    return application;
  } else {
    throw new Error('申请提交失败，请重试');
  }
}

// 更新申请状态
export function updateApplicationStatus(applicationId, status) {
  // 验证状态值
  const validStatuses = ['pending', 'accepted', 'rejected'];
  if (!validStatuses.includes(status)) {
    throw new Error('无效的申请状态');
  }

  // 更新申请状态
  const updatedApplication = {
    status: status,
    updatedAt: new Date().toISOString()
  };

  // 更新申请到存储
  if (updateApplication(applicationId, updatedApplication)) {
    return findApplicationById(applicationId);
  } else {
    throw new Error('申请状态更新失败，请重试');
  }
}

// 获取申请详情
export function getApplicationById(applicationId) {
  return findApplicationById(applicationId);
}

// 获取职位的所有申请
export function getApplicationsByJob(jobId) {
  return findApplicationsByJobId(jobId);
}

// 获取用户的所有申请
export function getApplicationsByApplicant(applicantId) {
  return findApplicationsByApplicantId(applicantId);
}

// 获取所有申请
export function getAllApplications() {
  return findAllApplications();
}

// 获取申请统计信息（用于职位列表显示申请人数）
export function getApplicationStats(jobId) {
  const applications = findApplicationsByJobId(jobId);
  
  const stats = {
    total: applications.length,
    pending: 0,
    accepted: 0,
    rejected: 0
  };
  
  applications.forEach(app => {
    if (app.status === 'pending') stats.pending++;
    if (app.status === 'accepted') stats.accepted++;
    if (app.status === 'rejected') stats.rejected++;
  });
  
  return stats;
}